﻿
/* $Id: PacketHandlers.cs 9 2011-04-20 09:17:32Z nramsbottom@gmail.com $ */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace SimpleNetServer
{
	delegate void OnPacketReceive(NetClient client, PacketReader reader);

	class PacketHandlers
	{

		static Dictionary<UInt32, PacketHandler> m_Handlers = new Dictionary<UInt32, PacketHandler>();

		static PacketHandlers()
		{
			// define packet handlers
			Register(0x1, 0, new OnPacketReceive(NoOp));
			Register(0x2, 64, new OnPacketReceive(Login));
			Register(0x4, 0, new OnPacketReceive(Motd));
			Register(0x5, 32, new OnPacketReceive(Command));
		} //

		static void Register(UInt32 packetId, int length, OnPacketReceive onReceive)
		{
			m_Handlers[packetId] = new PacketHandler(packetId, length, onReceive);
		} //

		public static PacketHandler GetHandler(UInt32 packetId)
		{
			if (m_Handlers.ContainsKey(packetId))
				return m_Handlers[packetId] as PacketHandler;
			return null;
		} //

		#region Packet Handler Implementations

		static void Login(NetClient client, PacketReader reader)
		{
			Debug.WriteLine("login packet handler invoked");

			var username = reader.ReadString(32).Trim();
			var password = reader.ReadString(32).Trim();
			var loggedIn = false;

			Debug.WriteLine(String.Format("Login as {0}:{1} attempted.", username, password));

			if (username == "username" && password == "password123")
			{
				if (client.LoggedIn)
					return; // already logged in. ignore packet.
				else
				{
					client.LoggedIn = true;
					loggedIn = true;
				}
			}

			client.Send(new LoginResponsePacket(loggedIn));
			
		} //

		static void NoOp(NetClient client, PacketReader reader)
		{
			client.Send(new NoOpResponsePacket());
		} //

		static void Motd(NetClient client, PacketReader reader)
		{
			client.Send(new MotdResponsePacket("Welcome to the server."));
		} //

		static void Command(NetClient client, PacketReader reader)
		{

			if (client.LoggedIn)
			{

				var cmd = reader.ReadString(32);

				Debug.WriteLine(string.Format("Client sent command '{0}'", cmd));
				client.Send(new CommandResponsePacket(true, "received command " + cmd));

			}
			else
			{
				Debug.WriteLine("Client sent command but is not logged in.");
				client.Send(new CommandResponsePacket(false, "not logged in"));
			}

		} //
		
		#endregion

	} // class
} // namespace
